package org.lc.platform.boot.controller;

import io.swagger.v3.oas.annotations.Hidden;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.lc.platform.base.enums.ResultCodeEnum;
import org.lc.platform.base.exception.BusinessException;
import org.lc.platform.base.exception.SystemException;
import org.lc.platform.base.result.Result;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Hidden()
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public Result<?> handleError(HttpServletRequest request) {
        // 获取异常信息
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        String message = (String) request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
        Object exception = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
        var res = Result.error(ResultCodeEnum.FAILED);
        if (exception instanceof BusinessException) {
            var code = ((BusinessException) exception).getCode();
            message = ((BusinessException) exception).getMsg();
            res.setCode(code);
        }

        if (exception instanceof SystemException) {
            var code = ((SystemException) exception).getCode();
            message = ((SystemException) exception).getMsg();
            res.setCode(code);
        }

        if (status.equals(HttpStatus.NOT_FOUND.value())) {
            message = "当前接口不存在！";
        }
        res.setMsg(message);
        return res;
    }
}
